'use strict';

const Service = require('egg').Service;

class QuestionAnswerService extends Service {
  // 根据题目ID获取答案
  async findByQuestionId(questionId) {
    const { ctx } = this;
    return await ctx.model.QuestionAnswer.findAll({
      where: { question_id: questionId },
      order: [['created_at', 'ASC']],
    });
  }

  // 根据ID获取答案
  async findById(id) {
    const { ctx } = this;
    return await ctx.model.QuestionAnswer.findByPk(id);
  }

  // 创建答案
  async create(data) {
    const { ctx } = this;
    return await ctx.model.QuestionAnswer.create(data);
  }

  // 更新答案
  async update(id, data) {
    const { ctx } = this;
    const answer = await ctx.model.QuestionAnswer.findByPk(id);
    if (answer) {
      await answer.update(data);
      return answer;
    }
    return null;
  }

  // 删除答案
  async delete(id) {
    const { ctx } = this;
    const answer = await ctx.model.QuestionAnswer.findByPk(id);
    if (answer) {
      await answer.destroy();
      return true;
    }
    return false;
  }
}

module.exports = QuestionAnswerService;
